package com.example.project7;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    private static final int LOGIN_SUCCESS = 1;
    private static final int LOGIN_FAILED = 0;
    private static final int LOGIN_START = 2;

    private EditText editTextUsername;
    private EditText editTextPassword;
    private CheckBox checkboxAgreement;
    private Button buttonLogin;
    private TextView tvRegister;
    private ProgressBar progressBar;
    private ImageView ivPasswordToggle;
    private boolean isPasswordVisible = false;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_START:
                    progressBar.setVisibility(View.VISIBLE);
                    buttonLogin.setEnabled(false);
                    Toast.makeText(LoginActivity.this, "登录中...", Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_SUCCESS:
                    progressBar.setVisibility(View.GONE);
                    buttonLogin.setEnabled(true);
                    Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                    String username = (String) msg.obj;
                    String userEmail = username + "@163.com";

                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("user_email", userEmail);
                    startActivity(intent);
                    finish();
                    break;

                case LOGIN_FAILED:
                    progressBar.setVisibility(View.GONE);
                    buttonLogin.setEnabled(checkboxAgreement.isChecked());
                    Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initViews();
        setupListeners();
    }

    private void initViews() {
        // ID 已经和 activity_login.xml 完全对应
        editTextUsername = findViewById(R.id.editText_username);
        editTextPassword = findViewById(R.id.editText_password);
        checkboxAgreement = findViewById(R.id.checkbox_agreement);
        buttonLogin = findViewById(R.id.button_login);
        tvRegister = findViewById(R.id.tv_register);
        progressBar = findViewById(R.id.progressBar);
        ivPasswordToggle = findViewById(R.id.iv_password_toggle);
    }

    private void setupListeners() {
        editTextUsername.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                editTextUsername.setText(editTextUsername.getText().toString().trim());
            }
        });

        checkboxAgreement.setOnCheckedChangeListener((buttonView, isChecked) -> {
            buttonLogin.setEnabled(isChecked);
        });

        buttonLogin.setOnClickListener(v -> {
            final String username = editTextUsername.getText().toString().trim();
            final String password = editTextPassword.getText().toString().trim();
            if (username.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!checkboxAgreement.isChecked()) {
                Toast.makeText(LoginActivity.this, "请同意用户协议", Toast.LENGTH_SHORT).show();
                return;
            }
            startLoginThread(username, password);
        });

        tvRegister.setOnClickListener(v -> Toast.makeText(LoginActivity.this, "跳转到注册页", Toast.LENGTH_SHORT).show());

        ivPasswordToggle.setOnClickListener(v -> {
            isPasswordVisible = !isPasswordVisible;
            if (isPasswordVisible) {
                editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_eye_visible); // 更换为“睁眼”图标
            } else {
                editTextPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                ivPasswordToggle.setImageResource(R.drawable.ic_eye_hidden); // 更换为“闭眼”图标
            }
            editTextPassword.setSelection(editTextPassword.getText().length());
        });
    }

    private void startLoginThread(final String username, final String password) {
        new Thread(() -> {
            handler.sendEmptyMessage(LOGIN_START);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if ("admin".equals(username) && "123456".equals(password)) {
                Message msg = handler.obtainMessage(LOGIN_SUCCESS);
                msg.obj = username;
                handler.sendMessage(msg);
            } else {
                handler.sendEmptyMessage(LOGIN_FAILED);
            }
        }).start();
    }
}